from flask import Blueprint, jsonify, request, current_app
from ..models.airport import Airport
from ..models.oil_tank import OilTank
from ..models.ammunition_depot import AmmunitionDepot
from ..models.parking_apron import ParkingApron
from .. import db
from sqlalchemy import func

bp = Blueprint('protection', __name__, url_prefix='/api/protection')

@bp.route('/query', methods=['GET'])
def query_protection():
    """根据查询条件获取防护设施数据"""
    protection_type = request.args.get('protectionType', 'aircraft')
    
    try:
        # 根据不同的防护类型返回不同的数据
        if protection_type == 'aircraft':
            return get_aircraft_protection()
        elif protection_type == 'oil':
            return get_oil_protection()
        elif protection_type == 'ammunition':
            return get_ammunition_protection()
        elif protection_type == 'parking':
            return get_parking_apron_protection()
        else:
            return jsonify({'error': f'不支持的防护类型: {protection_type}'}), 400
            
    except Exception as e:
        current_app.logger.error(f'查询防护设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

@bp.route('/initial', methods=['GET'])
def get_initial_data():
    """获取初始数据"""
    try:
        return jsonify({
            'regions': ['taipei', 'taichung', 'tainan'],
            'protectionTypes': [
                {'value': 'aircraft', 'name': '飞机防护'},
                {'value': 'oil', 'name': '油料防护'},
                {'value': 'ammunition', 'name': '弹药防护'},
                {'value': 'parking', 'name': '停机坪防护'}
            ]
        })
    except Exception as e:
        current_app.logger.error(f'获取初始数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def get_aircraft_protection():
    """获取飞机防护设施数据"""
    try:
        # 查询所有机场的飞机防护设施数据
        airports = db.session.query(
            Airport.id,
            Airport.name,
            Airport.region,
            Airport.latitude,
            Airport.longitude,
            Airport.cave_capacity.label('cave'),        # 洞库
            Airport.mask_capacity.label('mask'),        # 掩蔽库
            Airport.shelter_capacity.label('shelter'),  # 机库
            Airport.hangar_capacity.label('hangar'),    # 机棚
            Airport.mask_count.label('mask_count'),     # 飞机掩体
            Airport.aircraft_count.label('aircraft')    # 部署飞机数量
        ).all()
        
        # 格式化返回结果
        result = []
        categories = ['cave', 'mask', 'shelter', 'hangar', 'mask_count']
        category_names = ['洞库', '掩蔽库', '机库', '机棚', '飞机掩体']
        
        # 将数据按区域分组
        regions = {}
        for airport in airports:
            region = airport.region
            if region not in regions:
                regions[region] = []
            regions[region].append({
                'name': airport.name,
                'latitude': float(airport.latitude or 0),
                'longitude': float(airport.longitude or 0),
                'cave': float(airport.cave or 0),
                'mask': float(airport.mask or 0),
                'shelter': float(airport.shelter or 0),
                'hangar': float(airport.hangar or 0),
                'mask_count': float(airport.mask_count or 0),
                'aircraft': float(airport.aircraft or 0)
            })
        
        # 构建最终数据
        chart_data = {
            'categories': category_names,
            'airports': [a.name for a in airports],
            'series': [],
            'regions': []
        }
        
        # 为每个区域构建数据
        for region, airports_data in regions.items():
            region_item = {
                'name': get_region_name(region),
                'airports': []
            }
            
            for airport in airports_data:
                airport_item = {
                    'name': airport['name'],
                    'latitude': airport['latitude'],
                    'longitude': airport['longitude'],
                    'values': [
                        airport['cave'],
                        airport['mask'],
                        airport['shelter'],
                        airport['hangar'],
                        airport['mask_count']
                    ],
                    'aircraft': airport['aircraft']
                }
                region_item['airports'].append(airport_item)
            
            chart_data['regions'].append(region_item)
        
        return jsonify(chart_data)
        
    except Exception as e:
        current_app.logger.error(f'获取飞机防护设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def get_oil_protection():
    """获取油料防护设施数据"""
    try:
        # 查询所有机场的油料防护数据
        query = db.session.query(
            Airport.name,
            Airport.region,
            Airport.latitude,
            Airport.longitude,
            OilTank.id,
            OilTank.name.label('tank_name'),
            OilTank.type,
            OilTank.area,
            OilTank.location
        ).join(OilTank)
        
        oil_tanks = query.all()
        
        # 格式化数据
        airport_data = {}
        regions = {}
        oil_types = ['underground', 'semi_underground', 'ground']
        type_names = ['地下油罐', '半地下油罐', '地面油罐']
        
        # 分类处理类型
        def get_oil_type_category(type_str):
            if 'underground' in type_str.lower():
                return 'underground'
            elif 'semi' in type_str.lower() or 'half' in type_str.lower():
                return 'semi_underground'
            else:
                return 'ground'
        
        # 整理数据
        for item in oil_tanks:
            airport_name = item.name
            region = item.region
            lat = float(item.latitude or 0)
            lng = float(item.longitude or 0)
            oil_type = get_oil_type_category(item.type)
            area = float(item.area or 0)
            tank_name = item.tank_name
            tank_id = item.id
            location = item.location
            
            # 初始化机场数据
            if airport_name not in airport_data:
                airport_data[airport_name] = {
                    'name': airport_name,
                    'region': region,
                    'latitude': lat,
                    'longitude': lng,
                    'underground': 0,
                    'semi_underground': 0,
                    'ground': 0,
                    'tanks': []
                }
            
            # 添加面积数据
            airport_data[airport_name][oil_type] += area
            
            # 添加油罐详细信息
            airport_data[airport_name]['tanks'].append({
                'id': tank_id,
                'name': tank_name,
                'type': oil_type,
                'area': area,
                'location': location
            })
            
            # 分区域整理
            if region not in regions:
                regions[region] = []
        
        # 将机场添加到相应区域
        for airport_name, data in airport_data.items():
            region = data['region']
            if region not in regions:
                regions[region] = []
            regions[region].append(data)
        
        # 构建最终图表数据
        chart_data = {
            'categories': type_names,
            'regions': []
        }
        
        # 为每个区域构建数据
        for region, airports in regions.items():
            region_item = {
                'name': get_region_name(region),
                'airports': []
            }
            
            for airport in airports:
                airport_item = {
                    'name': airport['name'],
                    'latitude': airport['latitude'],
                    'longitude': airport['longitude'],
                    'values': [
                        airport['underground'],
                        airport['semi_underground'],
                        airport['ground']
                    ],
                    'tanks': airport['tanks']
                }
                region_item['airports'].append(airport_item)
            
            chart_data['regions'].append(region_item)
        
        return jsonify(chart_data)
        
    except Exception as e:
        current_app.logger.error(f'获取油料防护设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def get_ammunition_protection():
    """获取弹药防护设施数据"""
    try:
        # 查询所有机场的弹药防护数据
        query = db.session.query(
            Airport.name,
            Airport.region,
            Airport.latitude,
            Airport.longitude,
            AmmunitionDepot.id,
            AmmunitionDepot.name.label('depot_name'),
            AmmunitionDepot.type,
            AmmunitionDepot.area,
            AmmunitionDepot.location
        ).join(AmmunitionDepot)
        
        ammo_depots = query.all()
        
        # 格式化数据
        airport_data = {}
        regions = {}
        ammo_types = ['underground', 'semi_underground', 'ground']
        type_names = ['地下弹药库', '半地下弹药库', '地面弹药库']
        
        # 分类处理类型
        def get_ammo_type_category(type_str):
            if 'underground' in type_str.lower():
                return 'underground'
            elif 'semi' in type_str.lower() or 'half' in type_str.lower():
                return 'semi_underground'
            else:
                return 'ground'
        
        # 整理数据
        for item in ammo_depots:
            airport_name = item.name
            region = item.region
            lat = float(item.latitude or 0)
            lng = float(item.longitude or 0)
            ammo_type = get_ammo_type_category(item.type)
            area = float(item.area or 0)
            depot_name = item.depot_name
            depot_id = item.id
            location = item.location
            
            # 初始化机场数据
            if airport_name not in airport_data:
                airport_data[airport_name] = {
                    'name': airport_name,
                    'region': region,
                    'latitude': lat,
                    'longitude': lng,
                    'underground': 0,
                    'semi_underground': 0,
                    'ground': 0,
                    'depots': []
                }
            
            # 添加面积数据
            airport_data[airport_name][ammo_type] += area
            
            # 添加弹药库详细信息
            airport_data[airport_name]['depots'].append({
                'id': depot_id,
                'name': depot_name,
                'type': ammo_type,
                'area': area,
                'location': location
            })
            
            # 分区域整理
            if region not in regions:
                regions[region] = []
        
        # 将机场添加到相应区域
        for airport_name, data in airport_data.items():
            region = data['region']
            if region not in regions:
                regions[region] = []
            regions[region].append(data)
        
        # 构建最终图表数据
        chart_data = {
            'categories': type_names,
            'regions': []
        }
        
        # 为每个区域构建数据
        for region, airports in regions.items():
            region_item = {
                'name': get_region_name(region),
                'airports': []
            }
            
            for airport in airports:
                airport_item = {
                    'name': airport['name'],
                    'latitude': airport['latitude'],
                    'longitude': airport['longitude'],
                    'values': [
                        airport['underground'],
                        airport['semi_underground'],
                        airport['ground']
                    ],
                    'depots': airport['depots']
                }
                region_item['airports'].append(airport_item)
            
            chart_data['regions'].append(region_item)
        
        return jsonify(chart_data)
        
    except Exception as e:
        current_app.logger.error(f'获取弹药防护设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def get_parking_apron_protection():
    """获取停机坪防护设施数据"""
    try:
        # 查询所有机场的停机坪数据
        query = db.session.query(
            Airport.name,
            Airport.region,
            Airport.latitude,
            Airport.longitude,
            ParkingApron.id,
            ParkingApron.name.label('apron_name'),
            ParkingApron.type,
            ParkingApron.net_depth,
            ParkingApron.width,
            ParkingApron.parking_method,
            ParkingApron.quantity
        ).join(ParkingApron)
        
        aprons = query.all()
        
        # 格式化数据
        airport_data = {}
        regions = {}
        apron_types = ['individual', 'group', 'dispersed']
        type_names = ['个体停机坪', '群体停机坪', '分散停机坪']
        
        # 分类处理类型
        def get_apron_type_category(type_str):
            if 'individual' in type_str.lower() or '个体' in type_str:
                return 'individual'
            elif 'group' in type_str.lower() or '群体' in type_str:
                return 'group'
            else:
                return 'dispersed'
        
        # 整理数据
        for item in aprons:
            airport_name = item.name
            region = item.region
            lat = float(item.latitude or 0)
            lng = float(item.longitude or 0)
            apron_type = get_apron_type_category(item.type)
            apron_name = item.apron_name
            apron_id = item.id
            net_depth = float(item.net_depth or 0)
            width = float(item.width or 0)
            parking_method = item.parking_method
            quantity = int(item.quantity or 0)
            area = net_depth * width * quantity  # 计算面积
            
            # 初始化机场数据
            if airport_name not in airport_data:
                airport_data[airport_name] = {
                    'name': airport_name,
                    'region': region,
                    'latitude': lat,
                    'longitude': lng,
                    'individual': 0,
                    'group': 0,
                    'dispersed': 0,
                    'aprons': []
                }
            
            # 添加面积数据
            airport_data[airport_name][apron_type] += area
            
            # 添加停机坪详细信息
            airport_data[airport_name]['aprons'].append({
                'id': apron_id,
                'name': apron_name,
                'type': apron_type,
                'net_depth': net_depth,
                'width': width,
                'parking_method': parking_method,
                'quantity': quantity,
                'area': area
            })
            
            # 分区域整理
            if region not in regions:
                regions[region] = []
        
        # 将机场添加到相应区域
        for airport_name, data in airport_data.items():
            region = data['region']
            if region not in regions:
                regions[region] = []
            regions[region].append(data)
        
        # 构建最终图表数据
        chart_data = {
            'categories': type_names,
            'regions': []
        }
        
        # 为每个区域构建数据
        for region, airports in regions.items():
            region_item = {
                'name': get_region_name(region),
                'airports': []
            }
            
            for airport in airports:
                airport_item = {
                    'name': airport['name'],
                    'latitude': airport['latitude'],
                    'longitude': airport['longitude'],
                    'values': [
                        airport['individual'],
                        airport['group'],
                        airport['dispersed']
                    ],
                    'aprons': airport['aprons']
                }
                region_item['airports'].append(airport_item)
            
            chart_data['regions'].append(region_item)
        
        return jsonify(chart_data)
        
    except Exception as e:
        current_app.logger.error(f'获取停机坪防护设施数据失败: {str(e)}')
        return jsonify({'error': str(e)}), 500

def get_region_name(region_code):
    """根据区域代码获取区域名称"""
    region_names = {
        'taipei': '台北',
        'taichung': '台中',
        'tainan': '台南',
        'kaohsiung': '高雄',
        'hualien': '花莲',
        'taitung': '台东'
    }
    return region_names.get(region_code, region_code) 